package cn.chenxiejia;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: T2
 * @Description:
 * @Author: chenxiejia
 * @Date: 2022/2/7 12:33
 */
public class T2 {
    //CountDownLatch锁要先上锁执行await的线程后在执行后续线程
    static CountDownLatch latch = new CountDownLatch(3);
    //CyclicBarrier相比于上一个更加强大，在执行一定数量的await线程后，执行最后一个线程；
//    static CyclicBarrier cb = new CyclicBarrier(3, () -> {
//        System.out.println("人齐开饭！");
//    });

    public static void main(String[] args) {
        new Thread(() -> eat(6), "张三").start();
        new Thread(() -> eat(2), "李四").start();
        new Thread(() -> eat(7), "王五").start();
        //最后执行的线程
        new Thread(T2::starts).start();

    }

    //t为设置到场的时间
    static void eat(int t) {
        //获取当前线程名称
        String na = Thread.currentThread().getName();
        System.out.printf("%s需要%d秒到达...%n", na, t);
        try {
            //睡眠t时间后继续
            TimeUnit.SECONDS.sleep(t);
            System.out.println(na + "已到达！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        try {
//            cb.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (BrokenBarrierException e) {
//            e.printStackTrace();
//        }
        //countDown()的线程为标记线程
        latch.countDown();
    }

    static void starts() {
        try {
            //await()睡眠状态，直到设置的线程数量执行完才唤醒
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("人齐开饭");
    }
}
